package searchEngine;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Iterator;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SearchEngineServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp){
		try {
			String searchExpr = req.getParameter("searchExpr");
			String URL = req.getParameter("url");
			for (StringBuffer s1: SearchEngine.search(searchExpr, URL))
			{
				resp.getWriter().println(s1);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp){
		
		try {
			Iterator<StringBuffer> iterator;
			if(req.getCharacterEncoding() == null)
				   req.setCharacterEncoding("ISO-8859-1");
			String searchExpr = req.getParameter("searchExpr");
			String URL = req.getParameter("url");
			if(searchExpr.length()>3 && URL.length()>3){
				String[] stringUrlList = URL.split("\n");
				if(stringUrlList.length>1){
					HashSet<URL> urlList = new HashSet<URL>();
					for(String s: stringUrlList){ 
						try {
							urlList.add(new URL(s));
						}catch(MalformedURLException e){
							resp.getWriter().println("Exception:" + e.getMessage().toString()+ " caused by: \n" + searchExpr);
						}
					}
					iterator = SearchEngine.search(searchExpr, urlList).iterator();
				}else{
					iterator = SearchEngine.search(searchExpr, URL).iterator();
				}
				 while(iterator.hasNext()){
					resp.getWriter().println(iterator.next());
				 }
			}else resp.getWriter().println("The search criterions are invalid.");	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}
